# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from urllib.parse import urlparse
from fire_control_spider.config import DEBUG

def update_media_urls(item, media_urls):
    """更新媒体URLs到item中"""
    if not media_urls:
        return
    
    # 更新主文件
    if 'main_files' in media_urls and media_urls['main_files']:
        if 'main_files' not in item:
            item['main_files'] = []
        item['main_files'].extend(media_urls['main_files'])
    
    # 更新附件文件
    if 'attachment_files' in media_urls and media_urls['attachment_files']:
        if 'attachment_files' not in item:
            item['attachment_files'] = []
        item['attachment_files'].extend(media_urls['attachment_files'])
    
    # 更新图片
    if 'images' in media_urls and media_urls['images']:
        if 'images' not in item:
            item['images'] = []
        item['images'].extend(media_urls['images'])
    
    # 更新视频
    if 'videos' in media_urls and media_urls['videos']:
        if 'videos' not in item:
            item['videos'] = []
        item['videos'].extend(media_urls['videos'])

def extract_current_page_menu(response):
    """
    根据当前页面路径提取菜单层级信息
    Args:
        response: Scrapy响应对象
    Returns:
        list: 菜单层级数组，如 ['Home', 'About NFPA', 'Fire and Life Safety Ecosystem']
    """
    soup = BeautifulSoup(response.text, 'html.parser')
    current_url = response.url
    parsed_url = urlparse(current_url)
    current_path = parsed_url.path

    if DEBUG:
        print(f"[DEBUG] 当前页面URL: {current_url}")
        print(f"[DEBUG] 当前页面路径: {current_path}")

    if current_path and current_path != '/' and not current_path.endswith('/'):
        current_path = current_path + '/'
        if DEBUG:
            print(f"[DEBUG] 标准化后的路径: {current_path}")

    # 查找导航菜单
    navbar = soup.select_one('nav.navigation') or soup.select_one('ul.navbar-nav')
    if not navbar:
        if DEBUG:
            print("[DEBUG] 未找到导航菜单")
        return ['Home']

    if DEBUG:
        print(f"[DEBUG] 找到导航菜单，开始匹配...")

    nav_links = navbar.select('a')
    menu_hierarchy = []

    if DEBUG:
        print(f"[DEBUG] 找到 {len(nav_links)} 个导航链接")

    for link in nav_links:
        href = link.get('href', '')
        if not href:
            continue
        href_path = urlparse(href).path
        if href_path and href_path != '/' and not href_path.endswith('/'):
            href_path = href_path + '/'

        if DEBUG:
            print(f"[DEBUG] 检查链接: {href} -> {href_path}")

        if current_path == href_path:
            if DEBUG:
                print(f"[DEBUG] 找到精确匹配: {current_path} == {href_path}")
            menu_text = link.get_text(strip=True)
            if menu_text:
                menu_hierarchy.append(menu_text)
                if DEBUG:
                    print(f"[DEBUG] 当前菜单项: {menu_text}")
            break

    if DEBUG:
        print(f"[DEBUG] 最终菜单层级: {menu_hierarchy}")

    return ['Home'] + menu_hierarchy if menu_hierarchy else ['Home']